package org.example.Entity;

import org.example.Utils.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class FileFactory {


    public static MyFile getFileOnArgs(HashMap<String, String> args) {
        MyFile myFile = new MyFile();
        if (args.get("-t") != null) {
            List<String> time = StringUtils.getTimeUnit(args.get("-t"));
            int ttl = Integer.parseInt(time.get(0));
            myFile.setTtl(ttl);
            String timeUnit = time.get(1);
            if ("SECONDS".equalsIgnoreCase(timeUnit) || "sec".equalsIgnoreCase(timeUnit) || "s".equalsIgnoreCase(timeUnit))
                myFile.setTimeUnit(TimeUnit.SECONDS);
            else if ("DAYS".equalsIgnoreCase(timeUnit) || "d".equalsIgnoreCase(timeUnit))
                myFile.setTimeUnit(TimeUnit.DAYS);
            else if ("HOURS".equalsIgnoreCase(timeUnit) || "h".equalsIgnoreCase(timeUnit))
                myFile.setTimeUnit(TimeUnit.HOURS);
            else if ("MINUTES".equalsIgnoreCase(timeUnit) || "min".equalsIgnoreCase(timeUnit) || "m".equalsIgnoreCase(timeUnit))
                myFile.setTimeUnit(TimeUnit.MINUTES);
        }
        if (args.get("-d") != null) {
            int counts = Integer.parseInt(args.get("-d"));
            myFile.setCounts(Math.max(counts, 1));
        }
        if (args.get("-m") != null) {
            myFile.setContent(args.get("-m"));
        }
        Date date = new Date();
        myFile.setCreate_time(date);
        myFile.setUpdate_time(date);
        return myFile;
    }

    //判断是否过期,应该抽离成工具类的静态方法
    public static boolean isExpired(MyFile myFile) {
        if (myFile.getTtl() == null || myFile.getTimeUnit() == null) return false;
        return myFile.getCreate_time().getTime() + myFile.getTimeUnit().toMillis(myFile.getTtl()) < new Date().getTime();
    }
}
